package cn.cleanarch.infra.idp.pms.service.impl;

import cn.cleanarch.infra.idp.commons.domain.dto.PageResult;
import cn.cleanarch.infra.idp.commons.utils.Times;
import cn.cleanarch.infra.idp.pms.dao.repository.ProjectCategoryRepository;
import cn.cleanarch.infra.idp.pms.dao.repository.ProjectRepository;
import cn.cleanarch.infra.idp.pms.domain.dto.ProjectCategoryDTO;
import cn.cleanarch.infra.idp.pms.domain.dto.ProjectDTO;
import cn.cleanarch.infra.idp.pms.domain.entity.Project;
import cn.cleanarch.infra.idp.pms.domain.entity.ProjectCategory;
import cn.cleanarch.infra.idp.pms.domain.query.ProjectCategoryQuery;
import cn.cleanarch.infra.idp.pms.domain.query.ProjectQuery;
import cn.cleanarch.infra.idp.pms.service.ProjectCategoryService;
import cn.cleanarch.infra.idp.pms.service.ProjectService;
import cn.cleanarch.infra.idp.uaa.core.util.LoginSessionTool;

import java.time.LocalDateTime;
import cn.cleanarch.infra.idp.web.exception.Exceptions;
import cn.cleanarch.infra.idp.uaa.business.service.UserService;
import cn.cleanarch.infra.idp.uaa.core.domain.dto.UserQueryBuilder;
import cn.cleanarch.infra.idp.uaa.core.domain.vo.UserItemVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目服务实现类
 */
@Service
public class ProjectServiceImpl implements ProjectService {

    private final ProjectRepository projectRepository;
    private final ProjectCategoryRepository projectCategoryRepository;
    private final ProjectCategoryService projectCategoryService;
    private final UserService userService;

    public ProjectServiceImpl(ProjectRepository projectRepository, 
                             ProjectCategoryRepository projectCategoryRepository,
                             ProjectCategoryService projectCategoryService,
                             UserService userService) {
        this.projectRepository = projectRepository;
        this.projectCategoryRepository = projectCategoryRepository;
        this.projectCategoryService = projectCategoryService;
        this.userService = userService;
    }

    @Override
    public PageResult<ProjectDTO> pageQuery(ProjectQuery query) {
        // 使用自定义的分页查询方法
        Page<Project> page = projectRepository.pageQuery(query);
        
        // 手动转换Project实体到ProjectDTO
        List<ProjectDTO> dtoList = page.getRecords().stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
        
        return new PageResult<ProjectDTO>((int)page.getTotal(), dtoList);
    }

    @Override
    public Project getById(Long id) {
        return projectRepository.getById(id);
    }

    @Override
    @Transactional
    public ProjectDTO create(ProjectDTO dto) {
        Project project = new Project();
        project.setName(dto.getName());
        project.setDescription(dto.getDescription());
        project.setCategoryId(dto.getCategoryId());
        project.setStatus(dto.getStatus());
        project.setOwnerId(dto.getOwnerId());
        
        // 转换字符串时间为LocalDateTime
        if (dto.getStartDate() != null && !dto.getStartDate().isEmpty()) {
            project.setStartDate(LocalDateTime.parse(dto.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (dto.getEndDate() != null && !dto.getEndDate().isEmpty()) {
            project.setEndDate(LocalDateTime.parse(dto.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        project.setVisibility(dto.getVisibility());
        project.setEnable(dto.getEnable() != null ? dto.getEnable() : true);
        
        LocalDateTime now = LocalDateTime.now();
        project.setCreateTime(now);
        project.setUpdateTime(now);
        project.setCreateBy(LoginSessionTool.getCurrentUser().getUserId());
        project.setUpdateBy(LoginSessionTool.getCurrentUser().getUserId());

        projectRepository.save(project);
        
        return convertToDTO(project);
    }

    @Override
    @Transactional
    public ProjectDTO update(ProjectDTO dto) {
        Project existing = projectRepository.getById(dto.getId());
        if (existing == null) {
            Exceptions.throwException("项目不存在");
        }

        existing.setName(dto.getName());
        existing.setDescription(dto.getDescription());
        existing.setCategoryId(dto.getCategoryId());
        existing.setStatus(dto.getStatus());
        existing.setOwnerId(dto.getOwnerId());
        
        // 转换字符串时间为LocalDateTime
        if (dto.getStartDate() != null && !dto.getStartDate().isEmpty()) {
            existing.setStartDate(LocalDateTime.parse(dto.getStartDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (dto.getEndDate() != null && !dto.getEndDate().isEmpty()) {
            existing.setEndDate(LocalDateTime.parse(dto.getEndDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        existing.setVisibility(dto.getVisibility());
        existing.setEnable(dto.getEnable());
        existing.setUpdateTime(LocalDateTime.now());
        existing.setUpdateBy(LoginSessionTool.getCurrentUser().getUserId());
        
        projectRepository.updateById(existing);
        
        return convertToDTO(existing);
    }

    @Override
    @Transactional
    public Boolean delete(Long id) {
        if (id == null) {
            return false;
        }
        
        Project project = projectRepository.getById(id);
        if (project == null) {
            return false;
        }
        
        projectRepository.removeById(id);
        
        return true;
    }

    @Override
    public List<ProjectCategoryDTO> getProjectCategories() {
        ProjectCategoryQuery query = new ProjectCategoryQuery();
        PageResult<ProjectCategoryDTO> result = projectCategoryService.pageQuery(query);
        return result.getPageData();
    }

    @Override
    public List<ProjectCategoryDTO> getUsers() {
        return getUsers(null);
    }

    @Override
    public List<ProjectCategoryDTO> getUsers(String username) {
        // 调用用户服务获取用户列表
        UserQueryBuilder queryBuilder = new UserQueryBuilder();
        queryBuilder.setPageNo(1);
        queryBuilder.setPageSize(50); // 调整用户数量
        queryBuilder.setEnable(true); // 只获取启用的用户
        
        // 如果有搜索关键词，添加到查询条件中
        if (username != null && !username.trim().isEmpty()) {
            queryBuilder.setUsername(username.trim());
        }
        
        PageResult<UserItemVO> result = userService.pageQueryUsers(queryBuilder);
        
        // 转换为ProjectCategoryDTO格式
        return result.getPageData().stream()
            .map(this::convertUserItemVOToProjectCategoryDTO)
            .collect(Collectors.toList());
    }

    /**
     * 将UserItemVO转换为ProjectCategoryDTO格式
     */
    private ProjectCategoryDTO convertUserItemVOToProjectCategoryDTO(UserItemVO userItemVO) {
        ProjectCategoryDTO dto = new ProjectCategoryDTO();
        dto.setId(userItemVO.getId());
        dto.setName(userItemVO.getUsername());
        dto.setDescription(userItemVO.getNickName() != null ? userItemVO.getNickName() : userItemVO.getUsername());
        return dto;
    }

    /**
     * 将Project实体转换为ProjectDTO
     */
    public ProjectDTO convertToDTO(Project project) {
        ProjectDTO dto = new ProjectDTO();
        dto.setId(project.getId());
        dto.setName(project.getName());
        dto.setDescription(project.getDescription());
        dto.setCategoryId(project.getCategoryId());
        dto.setStatus(project.getStatus());
        dto.setOwnerId(project.getOwnerId());
        dto.setVisibility(project.getVisibility());
        dto.setEnable(project.getEnable());
        dto.setCreateTime(project.getCreateTime());
        dto.setUpdateTime(project.getUpdateTime());
        dto.setCreateBy(project.getCreateBy());
        dto.setUpdateBy(project.getUpdateBy());
        
        // 转换时间格式为字符串
        if (project.getStartDate() != null) {
            dto.setStartDate(project.getStartDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (project.getEndDate() != null) {
            dto.setEndDate(project.getEndDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        // 查询分类名称
        if (project.getCategoryId() != null) {
            ProjectCategory category = projectCategoryRepository.getById(project.getCategoryId());
            if (category != null) {
                dto.setCategoryName(category.getName());
            }
        }
        
        // 查询负责人姓名
        // 在实际项目中，这里应该查询用户服务获取用户名
        // 为了演示目的，使用固定值
        if (project.getOwnerId() != null) {
            switch (project.getOwnerId().intValue()) {
                case 1: dto.setOwnerName("管理员"); break;
                case 2: dto.setOwnerName("用户1"); break;
                case 3: dto.setOwnerName("用户2"); break;
                case 4: dto.setOwnerName("项目经理1"); break;
                case 5: dto.setOwnerName("项目经理2"); break;
                default: dto.setOwnerName("未知用户"); break;
            }
        }
        
        return dto;
    }
}